package com.stylefeng.guns.modular.pay.task;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.google.common.base.Strings;
import com.stylefeng.guns.core.util.HttpUtils;
import com.stylefeng.guns.core.util.JsonUtils;
import com.stylefeng.guns.core.util.MD5Utils;
import com.stylefeng.guns.modular.pay.exception.ApiException;
import com.stylefeng.guns.modular.pay.exception.BusException;
import com.stylefeng.guns.modular.pay.exception.ResultEnum;
import com.stylefeng.guns.modular.pay.model.Trans;
import com.stylefeng.guns.modular.pay.payment.jft.common.JftConfigure;
import com.stylefeng.guns.modular.pay.payment.jft.core.AESUtil;
import com.stylefeng.guns.modular.pay.payment.jft.core.MD5Util;
import com.stylefeng.guns.modular.pay.service.ITransService;

@Component
public class ScheduledService {
    private final static Logger log = LoggerFactory.getLogger(ScheduledService.class);
    @Autowired
    private ITransService transService;
    
	
	 @Scheduled(cron = "0 0/30 * * * *")
    public void scheduled(){
        log.info("=====>>>>>使用cron  {}","订单同步");
        List<Trans> list = transService.selectList(new EntityWrapper<Trans>().eq("status", 1));
        for(Trans trans:list){
        	orderSyn(trans);
        }
    }


	private void orderSyn(Trans trans) {
		Map<String,String> queryMap = new HashMap<String,String>();
		queryMap.put("verCode", "1001");
		queryMap.put("chMerCode", trans.getChMerCode());
		queryMap.put("orderCode", trans.getPlatOrderCode());
		Map<String,String> dataMap = new HashMap<String,String>();
		String resStr = "";
		try {
			String linkString = MD5Utils.createLinkString(queryMap); 
			String sign = MD5Util.encrypt(linkString+"&md5key="+JftConfigure.MD5_KEY, "UTF-8");
			byte[] encrypt = AESUtil.encryptAES(JsonUtils.mapToJson(queryMap).getBytes(), JftConfigure.AES_KEY.getBytes(), true, "UTF-8");
			//请求
			dataMap.put("orgCode",JftConfigure.ORG_CODE);
			dataMap.put("encryptData", new String(encrypt,"UTF-8"));
			dataMap.put("signData", sign);
			resStr = HttpUtils.post(JftConfigure.BASE_URL+"/fusionPosp/interface/tradeQuery", dataMap);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
//		log.info("resStr="+resStr);
		if(Strings.isNullOrEmpty(resStr)){
			throw new ApiException(ResultEnum.CHANNEL_RESPONSE_ERROR);
		}
		JSONObject jsonObject = JSON.parseObject(resStr);
		if(jsonObject.containsKey("resCode")&& !"0000".equals(jsonObject.getString("resCode"))){
			throw new BusException(jsonObject.getString("resCode"), jsonObject.getString("resMsg"));
		}
		String encryptData = jsonObject.getString("encryptData");
		byte[] resDate = null;
		try {
			resDate = AESUtil.decryptAES(encryptData.getBytes(), JftConfigure.AES_KEY.getBytes(), true, "UTF-8");
		} catch (Exception e) {
			throw new ApiException(ResultEnum.UNKONW_EXCEPTION);
		}
		JSONObject resObject = null;
		try {
			resObject = JSON.parseObject(new String(resDate,"UTF-8"));
		} catch (UnsupportedEncodingException e) {
			throw new ApiException(ResultEnum.UNKONW_EXCEPTION);
		}
		log.info("resObject="+resObject.toJSONString());
		String resCode = resObject.getString("resCode");
		if(resCode.equals("0000")){//成功
			update(resObject,trans.getId(),0);
		}else if("0002".equals(resCode)){//处理中
		
		}else{
			update(resObject,trans.getId(),2);
		}
	}


	private void update(JSONObject resObject, Integer id,Integer status) {
		Trans updateTrans = new Trans();
		updateTrans.setId(id);
		updateTrans.setTranStatus(status);
		if(Strings.isNullOrEmpty(resObject.getString("tranTime"))){
			updateTrans.setTranTime(resObject.getString("tranTime"));
		}
		if(Strings.isNullOrEmpty(resObject.getString("tranStatus"))){
			updateTrans.setTranStatus(resObject.getInteger("tranStatus"));
		}
		if(Strings.isNullOrEmpty(resObject.getString("drawStatus"))){
			updateTrans.setDrawStatus(resObject.getInteger("drawStatus"));
		}
		if(Strings.isNullOrEmpty(resObject.getString("drawAmount"))){
			updateTrans.setDrawAmount(resObject.getBigDecimal("drawAmount"));
		}
		transService.updateById(updateTrans);
	}

}
